package com.jing.ads.handler;

import java.io.UnsupportedEncodingException;

import org.apache.http.entity.StringEntity;
import org.json.JSONObject;

import com.jing.ads.application.MyApplication;
import com.jing.ads.model.AppInfo;
import com.jing.ads.model.Entry;
import com.jing.ads.services.QueueService;
import com.jing.ads.util.GlobalUtil;
import com.jing.ads.util.PreferenceUtil;

import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Build;
import android.text.TextUtils;

public class SendAppsHandler extends BaseHandler {
	
	private String imei = "";
	private String udid = "";
	private String data = "";
	
	private AppInfo info = null;
	
	public SendAppsHandler(Context context) {
		super(context);
		MyApplication app = (MyApplication) context.getApplicationContext();
		imei = app.getIMEI();
		udid = app.getUDID();
		info = new AppInfo();
		this.action = "sendapps";
	}
	
	public void setParams(String data) {
		this.data = data;
	}
	
	@Override
	protected void initRequest() {
		params.put("udid", udid);
		params.put("imei", imei);
		params.put("model", Build.MODEL);
		params.put("version", String.valueOf(versionCode));
	}

	@Override
	protected void initEntity() {
		if (!TextUtils.isEmpty(data)) {
			try {
				this.entity = new StringEntity(data, "utf-8");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
		}
	}

	@Override
	protected void onParser(JSONObject response) {
		try {
			JSONObject jo = response.optJSONObject("ap_config");
			if (!JSONObject.NULL.equals(jo)) {
				String s = jo.optString("scron", "");
				String g = jo.optString("gcron", "");
				String nv = jo.optString("newest_version", "");
				int nvc = jo.optInt("version_code", 0);
				long nsize = jo.optLong("apk_size", 0);
				info.setGcron(g);
				info.setScron(s);
				info.setNewVersion(nv);
				String gg = PreferenceUtil.getSharedString(context, QueueService.KEY_GET, "");
				String ss = PreferenceUtil.getSharedString(context, QueueService.KEY_SEND, "");
				if (!gg.equals(g)) {
					PreferenceUtil.putSharedString(context, QueueService.KEY_GET, g);
				}
				if (!ss.equals(s)) {
					PreferenceUtil.putSharedString(context, QueueService.KEY_SEND, s);
				}
				if(!TextUtils.isEmpty(nv)) {
					PreferenceUtil.putSharedString(context, "self_apk", nv);
					PreferenceUtil.putSharedInt(context, "self_apk_code", nvc);
					PreferenceUtil.putSharedLong(context, "self_apk_size", nsize);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public Entry getData() {
		return info;
	}

}
